// EmployeeGrid.js
"use client";
import React, { useCallback, useMemo, useRef, useState, useEffect } from "react";
import { AgGridReact } from "ag-grid-react";
import { batchProcessChangesByApi, getEmployeesWithPaginationByApi } from "./mockApi";
import { PrimaryKeyManager } from "./PrimaryKeyManager";

// 只注册必要的ag-Grid模块
import {
  ClientSideRowModelModule,
  DateEditorModule,
  HighlightChangesModule,
  LocaleModule,
  ModuleRegistry,
  NumberEditorModule,
  PaginationModule,
  RowApiModule,
  RowSelectionModule,
  SelectEditorModule,
  TextEditorModule,
  TextFilterModule,
  RowStyleModule,
  themeAlpine,
  themeBalham,
  themeMaterial,
  themeQuartz,
  ValidationModule
} from 'ag-grid-community';

// 导入中文本地化文本
import { AG_GRID_LOCALE_CN } from '@ag-grid-community/locale';
import {
  LicenseManager,
  ServerSideRowModelApiModule,
  ServerSideRowModelModule,
  SetFilterModule
} from 'ag-grid-enterprise';
import { agGridConfig, validateConfig } from "../../utils/config";
import styles from './EmployeeGrid.module.css';

ModuleRegistry.registerModules([
  HighlightChangesModule,
  ClientSideRowModelModule,
  NumberEditorModule,
  TextEditorModule,
  RowSelectionModule,
  SelectEditorModule,
  DateEditorModule,
  RowApiModule,
  TextFilterModule,
  RowStyleModule,
  SetFilterModule,
  PaginationModule,
  ServerSideRowModelApiModule,
  ServerSideRowModelModule,
  ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []),
  LocaleModule,
]);

// 验证配置并设置许可证密钥
validateConfig();
if (agGridConfig.licenseKey) {
  LicenseManager.setLicenseKey(agGridConfig.licenseKey);
} else {
  console.warn('ag-Grid 许可证密钥未配置，请检查环境变量 NEXT_PUBLIC_AG_GRID_LICENSE_KEY');
}

// 自定义主题配置 - 深色主题
const myTheme = themeQuartz
  .withParams({
    backgroundColor: "#1f2836",        // 背景色
    browserColorScheme: "dark",        // 浏览器颜色方案
    chromeBackgroundColor: {
      ref: "foregroundColor",
      mix: 0.07,
      onto: "backgroundColor"
    },
    foregroundColor: "#FFF",           // 前景色（文字颜色）
    headerFontSize: 14                 // 表头字体大小
  });

const themeMap = {
  myTheme: { agGridTheme: myTheme, toolbar: { background: '#232f3e', color: '#fff' } },
  quartz: { agGridTheme: themeQuartz, toolbar: { background: '#232f3e', color: '#fff' } },
  balham: { agGridTheme: themeBalham, toolbar: { background: '#f5f7fa', color: '#222' } },
  material: { agGridTheme: themeMaterial, toolbar: { background: '#fff', color: '#222' } },
  alpine: { agGridTheme: themeAlpine, toolbar: { background: '#f8fafb', color: '#222' } },
};

// 性别、部门等下拉选项
const genderOptions = ["男", "女"];
const departmentOptions = ["研发", "市场", "销售", "人事", "财务"];

// 服务端分页数据源配置
const getServerSideDatasource = () => ({
  // 获取数据的方法
  getRows: async (params) => {
    try {
      console.log('服务端分页参数:', params.request);
      // console.log('请求参数详情:', {
      //   startRow: params.request.startRow,
      //   endRow: params.request.endRow,
      //   sortModel: params.request.sortModel,
      //   filterModel: params.request.filterModel
      // });

      // 调用服务端分页接口
      const result = await getEmployeesWithPaginationByApi(params.request);
      console.log('服务端返回数据:', result);

      // 返回数据给AG Grid
      params.success({
        rowData: result.rows,
        rowCount: result.lastRow
      });
    } catch (error) {
      console.error('获取分页数据失败:', error);
      params.fail();
    }
  }
});

export default function EmployeeGrid() {

  // 容器样式配置
  const containerStyle = useMemo(() => ({
    width: "100%",
    height: "90%"
  }), []);

  // 网格样式配置
  const gridStyle = useMemo(() => ({
    height: "100%",
    width: "100%"
  }), []);

  const [themeKey, setThemeKey] = useState('quartz');
  const theme = themeMap[themeKey];

  // aggrid-toolbar主题色ref
  const toolbarRef = useRef(null);

  // 主题切换时动态设置CSS变量，仅影响aggrid-toolbar容器
  useEffect(() => {
    if (!toolbarRef.current) return;
    let bg = '#232f3e', color = '#fff';
    switch (themeKey) {
      case 'quartz':
        bg = '#fff'; color = '#222'; break;
      case 'balham':
        bg = '#f5f7fa'; color = '#222'; break;
      case 'material':
        bg = '#fff'; color = '#222'; break;
      case 'alpine':
        bg = '#f8fafb'; color = '#222'; break;
      case 'myTheme':
        bg = '#232f3e'; color = '#fff'; break;
      default:
        bg = '#fff'; color = '#222'; break;
    }
    toolbarRef.current.style.setProperty('--aggrid-toolbar-bg', bg);
    toolbarRef.current.style.setProperty('--aggrid-toolbar-color', color);
  }, [themeKey]);

  // 中文本地化文本
  const localeText = AG_GRID_LOCALE_CN;

  // ag-Grid 实例引用
  const gridRef = useRef(null);

  // 选中行
  const [selectedRows, setSelectedRows] = useState([]);
  // 统一的状态管理 - 记录所有待保存的更改
  const [pendingChanges, setPendingChanges] = useState({
    add: [],      // 新增的行数组
    update: {},   // 修改的行 {id: {field: value}}
    remove: []    // 删除的行ID数组
  });

  // 主键配置对象
  const primaryKeyConfig = {
    // 主键字段数组，支持单一或联合主键
    fields: ['id', 'name'], // 可配置为 ['id'] 或 ['id', 'name'] 或 ['id', 'name', 'department'] 等

    // 主键字段的数据类型
    fieldTypes: {
      id: 'number',
      name: 'string',
      department: 'string'
    },
  };
  // 初始化主键管理器
  const primaryKeyManager = useMemo(() => new PrimaryKeyManager(primaryKeyConfig), []);


  const getRowId = useCallback((params) => {
    // 使用primaryKey中的列的值组合成json字符串
    return primaryKeyManager.generateCompositeKey(params.data);
  }, [primaryKeyManager]);

  // 列定义，包含各种编辑器类型
  const columnDefs = [
    {
      field: "id",
      headerName: "ID",
      width: 70,
      editable: !primaryKeyConfig.fields.includes("id"),
      // checkboxSelection: true, // 显示选择框
      // headerCheckboxSelection: true // 表头显示全选框
    },
    { field: "name", headerName: "姓名", editable: !primaryKeyConfig.fields.includes("name"), cellEditor: "agTextCellEditor" },
    { field: "age", headerName: "年龄", editable: true, cellEditor: "agNumberCellEditor" },
    {
      field: "gender", headerName: "性别", editable: true,
      filter: "agTextColumnFilter",
      cellEditor: "agSelectCellEditor",
      cellEditorParams: { values: genderOptions }
    },
    {
      field: "department", headerName: "部门", editable: true,
      filter: 'agSetColumnFilter',
      filterParams: {
        values: departmentOptions
      },
      cellEditor: "agSelectCellEditor",
      cellEditorParams: { values: departmentOptions }
    },
    {
      field: "status", headerName: "在职", editable: true,
      cellEditor: "agSelectCellEditor",
      cellEditorParams: { values: [true, false] },
      valueFormatter: p => p.value ? "在职" : "离职"
    },
    {
      field: "join_date", headerName: "入职日期", editable: true,
      cellEditor: "agDateStringCellEditor"
    },
    // {
    //   headerName: "操作",
    //   field: "actions",
    //   cellRenderer: params => {
    //     return (
    //       <button
    //         className="aggrid-delete-btn styled-delete-btn"
    //         onClick={e => {
    //           e.stopPropagation(); // 阻止事件冒泡，防止 onCellClicked和onSelectionChanged 再触发
    //           if (window.confirm('确定要删除该行吗？')) {
    //             handleDelete(params.data.id);
    //           }
    //         }}
    //       >
    //         删除
    //       </button>
    //     );
    //   },
    //   width: 90,
    //   suppressMenu: true,
    //   suppressExport: true,
    //   editable: false
    // }
  ];

  // 处理网格准备就绪事件, 加载数据
  const onGridReady = useCallback((params) => {
    console.log('网格准备就绪，服务端分页模式');
    // 设置服务端数据源
    console.log('设置服务端数据源');
    if (params && params.api) {
      const datasource = getServerSideDatasource();
      params.api.setGridOption("serverSideDatasource", datasource);
    }
  }, []);



  // 行选中
  function onSelectionChanged() {
    if (gridRef.current && gridRef.current.api) {
      const selected = gridRef.current.api.getSelectedRows();
      console.log("onSelectionChanged selected", selected);
      setSelectedRows(selected);
    }
  }

  // 处理单元格点击事件，专门处理删除按钮
  function onCellClicked(params) {
    console.log("params", params);

    if (
      params.colDef.field === "actions" &&
      params.event.target &&
      params.event.target.classList.contains("aggrid-delete-btn")
    ) {
      // handleDelete(params.data.id);
      return;
    } else {
      // 只选中当前点击的行
      if (params.api) {
        params.api.deselectAll();
        params.node.setSelected(true, false); // 只选中当前行，不保留其它选中
        setSelectedRows([params.data]);
      }
    }
  }


  // 新增一行（服务端分页模式下，新增操作需要通过接口实现）
  const handleAdd = useCallback(() => {
    console.log("handleAdd");
    const temporaryKey = primaryKeyManager.generateTemporaryKey();
    const newRow = {
      ...temporaryKey
    };

    // 添加到新增行记录中
    setPendingChanges(prev => ({
      ...prev,
      add: [...prev.add, newRow]
    }));

    const selectedRows = gridRef.current.api.getSelectedNodes();
    console.log("selectedRows", selectedRows);

    if (selectedRows.length > 0) {
      // 在选中行前插入
      const rowIndex = selectedRows[0].rowIndex;
      const transaction = {
        addIndex: rowIndex != null ? rowIndex : undefined,
        add: [newRow],
      };
      gridRef.current.api.applyServerSideTransaction(transaction);
    } else {
      // 添加到当前页第一行
      const transaction = {
        addIndex: 0,
        add: [newRow],
      };
      gridRef.current.api.applyServerSideTransaction(transaction);
    }
  }, [primaryKeyManager]);



  // 单元格变更时记录变动
  function onCellValueChanged(params) {
    console.log("onCellValueChanged params", params);
    if (params && params.data) {
      const data = params.data;
      const field = params.colDef.field;
      const value = params.newValue;


      // 获取当前行的复合主键
      const currentCompositeKey = primaryKeyManager.generateCompositeKey(data);

      // 检查是否是修改新增的行
      const isNewRow = pendingChanges.add.some(row => primaryKeyManager.compareKeys(row, data));
      if (isNewRow) {
        console.log("修改新增行", data);
        // 更新新增记录中的对应行
        setPendingChanges(prev => ({
          ...prev,
          add: prev.add.map(row => primaryKeyManager.compareKeys(row, data) ? { ...row, [field]: value } : row)
        }));
        return;
      } else {
        // 记录修改已存在的行
        console.log("修改已存在行", data);
        setPendingChanges(prev => ({
          ...prev,
          update: {
            ...prev.update,
            [currentCompositeKey]: { ...prev.update[currentCompositeKey], [field]: value }
          }
        }));
      }

      // 进行服务端事务（只对已存在的行）
      if (gridRef.current && gridRef.current.api) {
        const transaction = {
          update: [{ ...params.data, [field]: value }],
        };
        gridRef.current.api.applyServerSideTransaction(transaction);
      }

      // console.log("pendingChanges", pendingChanges); // 此时还无法获取到最新数据
    }
  }


  // 删除
  const removeRow = useCallback(() => {
    const selectedRows = gridRef.current.api.getSelectedNodes();
    if (selectedRows.length === 0) {
      console.log("[Example] No row selected.");
      return;
    } else {
      console.log("try removeRow", selectedRows)
    }

    // 遍历selectedRows，删除
    selectedRows.forEach(row => {
      const data = row.data;
      const currentCompositeKey = primaryKeyManager.generateCompositeKey(data);
      console.log("deleteRow", currentCompositeKey);

      // 检查删除的行类型并更新相应的记录
      const isNewRow = pendingChanges.add.some(row => primaryKeyManager.compareKeys(row, data));
      const isModifiedRow = pendingChanges.update[currentCompositeKey];

      if (isNewRow) {
        // 删除新增行：从add记录中移除
        console.log("删除新增行", currentCompositeKey);
        setPendingChanges(prev => ({
          ...prev,
          add: prev.add.filter(row => !primaryKeyManager.compareKeys(row, data))
        }));
      } else if (isModifiedRow) {
        // 删除已修改行：从update记录中移除，添加到remove记录
        console.log("删除已修改行", currentCompositeKey);
        setPendingChanges(prev => {
          const newUpdate = { ...prev.update };
          delete newUpdate[currentCompositeKey];
          return {
            ...prev,
            update: newUpdate,
            remove: [...prev.remove, currentCompositeKey]
          };
        });
      } else {
        // 删除普通行：添加到remove记录
        console.log("记录删除的行", currentCompositeKey);
        // 需要去重，可以先检查remove中是否已经存在currentCompositeKey，如果存在则不添加
        setPendingChanges(prev => ({
          ...prev,
          remove: [...prev.remove, currentCompositeKey].filter((key, index, self) => self.indexOf(key) === index)
        }));
      }


      // const transaction = { remove: [data] };

      const transaction = {
        update: [{ ...data, isDeleted: true }],
      };
      gridRef.current.api.applyServerSideTransaction(transaction);

    });
    // console.log("pendingChanges", pendingChanges); // 此时还无法获取到最新数据
  }, [primaryKeyManager, pendingChanges]);

  // 保存更改 - 使用统一批量操作接口
  async function handleSaveChanges() {
    try {
      if (!gridRef.current || !gridRef.current.api) {
        throw new Error('Grid API not ready');
      }
      console.log("handleSaveChanges", pendingChanges);
      const { add, update, remove } = pendingChanges;

      // 检查是否有待保存的更改
      if (add.length === 0 && Object.keys(update).length === 0 && remove.length === 0) {
        alert("没有待保存的更改");
        return;
      }

      // 准备统一批量操作的数据ss
      const changes = {
        // 去除add中的临时主键
        add: add,
        update: Object.entries(update).map(([keys, changes]) => ({
          keys: primaryKeyManager.parseCompositeKey(keys),
          changes
        })),
        remove: remove.map(row => primaryKeyManager.parseCompositeKey(row))
      };

      console.log("统一批量操作数据:", changes);

      // 调用统一批量操作接口
      const result = await batchProcessChangesByApi(changes, primaryKeyConfig);

      if (result.success) {
        console.log("批量操作结果:", result);

        // 显示操作结果
        const message = [
          `新增: ${result.data.addedCount} 行`,
          `修改: ${result.data.updatedCount} 行`,
          `删除: ${result.data.removedCount} 行`
        ].join(', ');

        alert(`批量保存成功！${message}`);
      } else {
        // 处理部分失败的情况
        const errorMessage = result.errors.join('\n');
        alert(`批量保存部分失败：\n${errorMessage}`);
      }

      // 刷新数据源
      if (gridRef.current && gridRef.current.api) {
        gridRef.current.api.refreshServerSide();
        // const datasource = getServerSideDatasource();
        // gridRef.current.api.setGridOption("serverSideDatasource", datasource);
      }

      // 清空所有记录
      setPendingChanges({ add: [], update: {}, remove: [] });

    } catch (error) {
      console.error('批量保存失败:', error);
      alert(`批量保存失败：${error.message || error}`);
    }
  }

  const onPaginationChanged = useCallback((params) => {
    // 如果分页数据发生变化，则刷新服务端数据
    if (params.newData || params.newPage || params.newPageSize) {
      console.log("onPaginationChanged params", params);
      gridRef.current.api.stopEditing(true);
      // gridRef.current.api.cancelServerSideTransaction();
      // const pageSize = gridRef.current.api.paginationGetPageSize();
      // console.log("pageSize", pageSize);
      // const pageIndex = gridRef.current.api.paginationGetCurrentPage();
      // console.log("pageIndex", pageIndex);
      // const totalPages = gridRef.current.api.paginationGetTotalPages();
      // console.log("totalPages", totalPages);
      // const totalRows = gridRef.current.api.paginationGetRowCount();
      // console.log("totalRows", totalRows);
      // gridRef.current.api.refreshServerSide();
    }
  }, []);

  const rowClassRules = useMemo(() => {
    return {
      // row style function
      "strikethrough-container": (params) => {
        // console.log("rowClassRules params", params);
        return params.data?.isDeleted ?? false;
        // return numSickDays >= 23;
      },
      // row style expression
      // "sick-days-breach": "data.age < 23",
    };
  }, []);

  return (
    <div style={containerStyle}>
      {/* 工具栏，左侧增加主题切换下拉框 */}
      <div className={styles['aggrid-toolbar']} ref={toolbarRef}>
        {/* 主题切换下拉框 */}
        <div className="theme-select-container">
          <span style={{ fontWeight: 600, marginRight: 6 }}>主题：</span>
          <select
            value={themeKey}
            onChange={e => setThemeKey(e.target.value)}
            className="theme-select"
          >
            <option value="myTheme">MyTheme</option>
            <option value="quartz">Quartz</option>
            <option value="balham">Balham</option>
            <option value="material">Material</option>
            <option value="alpine">Alpine</option>
          </select>
        </div>



        {/* 其余操作按钮 */}
        <div className={styles['aggrid-btn-container']}>
          <button className={styles['aggrid-btn']} onClick={handleAdd}>添加行</button>
          <button className={styles['aggrid-btn-danger']} onClick={removeRow} style={{ marginLeft: 8 }} disabled={selectedRows.length === 0}>删除行</button>
          <button className={styles['aggrid-btn']} onClick={handleSaveChanges} style={{ marginLeft: 8 }} disabled={pendingChanges.add.length === 0 && Object.keys(pendingChanges.update).length === 0 && pendingChanges.remove.length === 0}>保存更改</button>
        </div>
        {/* 状态显示 */}
        <div className={styles['status-display']}>
          <span style={{ marginRight: 10 }}>
            新增: {pendingChanges.add.length} 行
          </span>
          <span style={{ marginRight: 10 }}>
            修改: {Object.keys(pendingChanges.update).length} 行
          </span>
          <span style={{ marginRight: 10 }}>
            删除: {pendingChanges.remove.length} 行
          </span>
        </div>
      </div>

      {/* 按钮样式，主色/危险色根据当前主题动态变化 */}
      <div style={gridStyle}>
        <AgGridReact
          ref={gridRef}
          rowData={undefined} // 服务端分页时不使用rowData
          columnDefs={columnDefs}
          defaultColDef={{ flex: 1, minWidth: 100, resizable: true, editable: true, enableCellChangeFlash: true }}
          getRowId={getRowId}
          rowSelection={{ mode: "multiRow" }}
          onSelectionChanged={onSelectionChanged}
          onCellClicked={onCellClicked}
          onCellValueChanged={onCellValueChanged}
          onGridReady={onGridReady}
          theme={theme.agGridTheme ?? myTheme}
          localeText={localeText}
          // 分页配置
          pagination={true} // 启用分页
          paginationPageSize={10} // 每页显示行数
          paginationPageSizeSelector={[5, 10, 20, 50]} // 分页大小选择器
          // 服务端分页配置
          rowModelType={"serverSide"} // 使用服务端行模型
          cacheBlockSize={10} // 缓存块大小（固定为20）
          onPaginationChanged={onPaginationChanged}
          multiSortKey={"ctrl"}
          rowClassRules={rowClassRules}
        />
      </div>
      <style>
        {`
          .strikethrough-container {
            background-color: #f2f2f2;
            color: #b5b5b5;
        }
        
        .strikethrough-container div {
            text-decoration: line-through;
            color: #838383;
        }
        `}
      </style>
    </div>
  );
}